﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ExcellOnServices.Models;
using ExcellOnServices.Models.Utils;
using System.Web.Security;

namespace ExcellOnServices.Controllers
{
	public class RegisterController : BaseController
	{
		[OutputCache(CacheProfile = "Common")]
		public ActionResult Index() {
			return View();
		}

		[OutputCache(CacheProfile = "Common")]
		public ActionResult Success() {
			return View();
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Index(CompanyRegister acc) {
			try {
				if (ModelState.IsValid) {
					acc.RegisterAccount.Roles_Id = 2;
					acc.RegisterAccount.Password = "password";
					acc.RegisterAccount.CreatedDateTime = DateTime.Now;

                    Account ac = db.Accounts.Where(c => c.Email.Equals(acc.RegisterAccount.Email)).FirstOrDefault();
                    if (ac != null)
                    {
                        ModelState.AddModelError("", "Email is exists");
                        return View();
                    }
					acc.RegisterCompany.Status = Accounts_Company.StatusType.Pending;
					acc.RegisterCompany.Account = acc.RegisterAccount;
					acc.RegisterAccount.Accounts_Company = acc.RegisterCompany;

					db.Accounts.Add(acc.RegisterAccount);
					db.Accounts_Company.Add(acc.RegisterCompany);

					db.SaveChanges();

					return RedirectToAction("Success");
				}
			} catch (DataException ex) {
				ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator." + ex.Message);
			}

			return View(acc);
		}
	}
}
